package cn.edu.jxau.test;

import java.util.Arrays;
import java.util.Objects;

public class Main {

	public static void main(String[] args) {

		Node node1 = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		Node node5 = new Node(5);
		Node node6 = new Node(6);
		Node node7 = new Node(7);
		node1.next = node2;
		node2.next = node3;
		node3.next = node6;
		node6.next = node7;

		node4.next = node5;
		node5.next = node6;
		System.out.println(foo(node1,node4).data);
	}

	public static Node foo(Node list1, Node list2) {

		// 1.参数校验 //
		Objects.requireNonNull(list1, "参数lsit1不能为null");
		Objects.requireNonNull(list2, "参数list2不能为null");

		// 2.求出list1、list2的长度 //
		int len1 = 0;
		int len2 = 0;
		Node cur = list1;
		while (cur != null) {
			len1++;
			cur = cur.next;
		}
		cur = list2;
		while (cur != null) {
			len2++;
			cur = cur.next;
		}

		// 3.找出第一个公共结点 //
		int x = len1 > len2 ? len1 - len2 : len2 - len1;
		Node cur1 = list1;
		Node cur2 = list2;
		if (len1 > len2) {
			for (int i = 0; i < x; i++) {
				cur1 = cur1.next;
			}
		} else {
			for (int i = 0; i < x; i++) {
				cur2 = cur2.next;
			}
		}
		while (cur1 != cur2) {
			cur1 = cur1.next;
			cur2 = cur2.next;
		}
		if (cur1 == null) { // 无公共节点
			return null;
		} else {
			return cur1;
		}
	}
}

class Node {
	public int data;
	public Node next;

	public Node(int data) {
		this.data = data;
	}
}
